package io.kiki.sba.registry.server.clientInterface.push;

import io.kiki.sba.registry.server.clientInterface.bootstrap.Config;
import io.kiki.sba.registry.server.clientInterface.metadata.MetadataCacheRegistry;
import io.kiki.sba.registry.server.clientInterface.providedata.FetchGrayPushSwitchService;
import io.kiki.sba.registry.server.clientInterface.providedata.FetchStopPushService;
import io.kiki.sba.registry.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Set;

public class PushSwitchService {

    @Autowired
    private Config config;

    @Resource
    private FetchGrayPushSwitchService fetchGrayPushSwitchService;

    @Resource
    private FetchStopPushService fetchStopPushService;

    @Autowired
    private MetadataCacheRegistry metadataCacheRegistry;

    public boolean canPushMultiDataCenter(Set<String> dataCenterSet) {
        StringUtil.checkNotEmpty(dataCenterSet, "push.dataCenters");
        for (String dataCenter : dataCenterSet) {
            if (!dataCenterCanPush(dataCenter)) {
                return false;
            }
        }
        return true;
    }

    private boolean dataCenterCanPush(String dataCenter) {
        if (config.isLocalDataCenter(dataCenter)) {
            return pushEnable(config.getDataCenter()) || CollectionUtils.isNotEmpty(fetchGrayPushSwitchService.getOpenIps());
        }

        return pushEnable(dataCenter);
    }

    public boolean canLocalDataCenterPush() {
        return dataCenterCanPush(config.getDataCenter());
    }

    public boolean canIpPushMulti(String ip, Set<String> dataCenters) {
        StringUtil.checkNotBlank(ip, "push.ip");
        StringUtil.checkNotEmpty(dataCenters, "push.dataCenters");

        for (String dataCenter : dataCenters) {
            if (!dataCenterAndIpCanPush(dataCenter, ip)) {
                return false;
            }
        }
        return true;
    }

    public boolean canIpPushLocal(String ip) {
        StringUtil.checkNotBlank(ip, "push.ip");
        return dataCenterAndIpCanPush(config.getDataCenter(), ip);
    }

    private boolean pushEnable(String dataCenter) {
        if (config.isLocalDataCenter(dataCenter)) {
            return !fetchStopPushService.isStopPushSwitch() || CollectionUtils.isNotEmpty(fetchGrayPushSwitchService.getOpenIps());
        }

        return metadataCacheRegistry.getPushEnableDataCenters().contains(dataCenter);
    }

    private boolean dataCenterAndIpCanPush(String dataCenter, String ip) {

        if (config.isLocalDataCenter(dataCenter)) {
            return !fetchStopPushService.isStopPushSwitch() || fetchGrayPushSwitchService.getOpenIps().contains(ip);
        }

        return metadataCacheRegistry.getPushEnableDataCenters().contains(dataCenter);
    }


}
